const schedule = require('node-schedule');
const sequelize = appRequire('db');

const userModel = appRequire('models/user');
const artPPTModel = appRequire('models/artPPT');
const miniSendTemplateMsg = appRequire('controllers/wx/sendTemplateMsg');
const { Op } = require("sequelize");

scheduleCronstyle();

//定时任务推送商品预警
function scheduleCronstyle() {
    schedule.scheduleJob('0 0 8 * * *', function () {
        batchTask(0);
        console.log('scheduleCronstyle:' + new Date());
    });
}

//批量预警推送服务
async function batchTask(index) {
    let pageSize = 10000;
    let thisUsers = await userModel.user.findAll({
        where: {
            wcMiniId: { [Op.ne]: null },
        },
        limit: pageSize,
        offset: pageSize * index,
    })
    thisUsers = Common.clone(thisUsers)

    if (thisUsers.length == 0) {
        return false
    } else {
        let lastResult = await getLastDayUpdate()
        for (let user of thisUsers) {
            let req = {
                body: {
                    uid: user.objectId,
                    pptNum: lastResult.data,
                    source:"01"
                }
            }
            miniSendTemplateMsg.sendJzzsRecordTemplateMsg(req)
        }

        batchTask(index + 1)
    }
}


async function getLastDayUpdate() {
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let day1 = new Date();
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
    let month = day1.getMonth() + 1 < 10 ? '0' + (day1.getMonth() + 1) : day1.getMonth() + 1
    let s1 = day1.getFullYear() + "-" + month + "-" + day1.getDate();

    let course = await artPPTModel.count({
        where: {
            createdAt: {
                [Op.gt]: s1 + ' 00:00:01',
                [Op.lt]: s1 + ' 23:59:59'
            },
        },
    })

    returnData.data = course
    return returnData
}